package emulator.util;

import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;

import emulator.analyzer.util.RangeRelocation;

public class AddressRangeList {
	List<AddressRange> the_list = new LinkedList<AddressRange>();
	
	public AddressRangeList(boolean [] address_field) {
		AddressRange range = null;
		for (int i = 0; i < address_field.length; i++)
		{
			if (address_field[i])
			{
				if (range == null)
				{
					range = new AddressRange();
					range.setStart(i);
				}
			}
			else
			{
				if (range != null)
				{
					range.setEnd(i-1);
					the_list.add(range);
					range = null;
				}
			}
		}
		if (range != null)
		{
			range.setEnd(address_field.length-1);
			the_list.add(range);
		}
	}

	public void dump(PrintStream out, String prefix) {
		if (the_list.isEmpty())
			out.println(prefix+"(none)");
		else
			for (AddressRange range : the_list)
				out.println(prefix+range);
	}

	public void toRelocations(List<RangeRelocation> relocations, int base) {
		for (AddressRange range : the_list)
		{
			relocations.add(new RangeRelocation(range, base - range.getStart()));
			base += range.getWidth();
		}
	}

	public boolean isEmpty() {
		return the_list.isEmpty();
	}
}
